package socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerThread extends Thread{

	private Socket socket;
	
	public ServerThread(Socket socket) {
		 this.socket = socket;
	}
	
	
	@Override
	public void run() {
		InputStream is = null;
		InputStreamReader isr = null;
		BufferedReader br = null;
		OutputStream os = null;
		PrintWriter pw = null;
		//获取输入流，并读取客户端信息
		try {
			is = socket.getInputStream();
			isr = new InputStreamReader(is);
			br = new BufferedReader(isr);
			StringBuilder sb = new StringBuilder();
			String line = null;
			
			while((line = br.readLine())!=null) {
				sb.append(line);
			}
			System.out.println(sb.toString());
			socket.shutdownInput();
			
			//获取客户端相关信息
			InetAddress address = socket.getInetAddress();
			System.out.println(address.getHostName()+"连接");
			//相应信息
			os = socket.getOutputStream();
			pw = new PrintWriter(os);
			pw.write("欢迎您！！！"+address.getHostAddress());
			pw.flush();
			socket.shutdownOutput();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			//关闭资源
			try {
				if(pw != null)
					pw.close();
				if(os != null)
					os.close();
				if(br != null)
					br.close();
				if(isr != null)
					isr.close();
				if(is != null)
					is.close();
				if(socket != null)
					socket.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}	
	
	public static void main(String[] args) throws IOException {
		ServerSocket ss = new ServerSocket(8080);
		System.out.println("服务器启动....");
		while(true) {
			
			Socket socket = ss.accept();
			ServerThread st = new ServerThread(socket);
			st.start();
		}
	}
	
	
}
